/*
 * EmployeeSaveServlet.java
 * Created on 25. juni 2008, 12:12
 */
package webshop.del;

import java.io.IOException;
import java.io.PrintWriter;
import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.transaction.UserTransaction;
import webshop.data.del.Department;
import webshop.data.del.Employee;



/**
 * EmployeeSaveServlet
 * @author even
 */
public class EmployeeSaveServlet extends AbstractDepartmentServlet {
    @Resource
    UserTransaction tx;
    
    /**
     * Handle requests. Sends a html page containing the department list.
     *
     * @param req the request object
     * @param resp the response object
     *
     * @throws IOException
     * @throws ServletException
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        Employee emp = null;
        Department dep = null;
        String empnoString = request.getParameter("empno");
        String depnoString = request.getParameter("depno");
        
        EntityManager em = emf.createEntityManager();

        PrintWriter out = response.getWriter();
            
        response.setContentType("text/html");
        response.setHeader("Cache-control", "no-cache");
        response.setHeader("Expires", "0");

        out.println("<html><head><title>"+this.getClass().getName()+"</title></head><body>");
        out.println("<h1>Save Employee</h1>");
        try {
            tx.begin();
            
            long depno = Long.valueOf(depnoString);
            dep = em.find(Department.class, depno);

            if (empnoString != null) {
                long empno = Long.valueOf(empnoString);
                emp = em.find(Employee.class, empno);
            }
            else {
                emp = new Employee();
                em.persist(emp);
            }
            
            String name = request.getParameter("name");
            emp.setName(name);
            String sal = request.getParameter("salary");
            emp.setSalary(Long.valueOf(sal));
            dep.addEmployee(emp);
            tx.commit();
            out.println("<p>Employee saved</p>");
        }
        catch (Exception e) {
            out.println("<p>Save employee failed, because of:</p>");
            out.println("<pre>");
            e.printStackTrace(out);
            out.println("</pre>");
        }

        out.println("<hr/>");
        out.print("<p><a href=\"index.html\">Home</a>");
        out.print(" &gt; <a href=\"deplist\">Department List</a>");
        out.println(" &gt; <a href=\"depedit?depno="+depnoString+"\">Department</a></p>");
        out.println("</body>");
        out.println("</html>");
    }    
}
